﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Xml;
using System.Configuration;
//using ICSharpCode.AvalonEdit.Highlighting;
using SmartMD.DataModel;
using SmartMD.Manager.StartPage;
using Techstar.Controls;
using Techstar.Dialog;
using Techstar.Net;
using Techstar.Progress;
using Border = System.Windows.Controls.Border;
using SmartMD.Manager.Specimens;
using SmartMD.Manager.Patient;
using SmartMD.Manager.Container;
using SmartMD.Manager.SysInfo;
using SmartMD.DataAccess.Oracle;
using SmartMD.Manager.Common;
using SmartMD.DataModel.Entity;
using SmartMD.Manager.SysInfo.User;
using SmartMD.DataAccess.Postgresql;
using SmartMD.DataAccess.Service;

namespace SmartMD.Manager
{
    /// <summary>
    /// Interaction logic for MainWindow2.xaml
    /// </summary>
    public partial class MainWindow
    {
        private static MainWindow _instance;
        private static bool _onLine;
        private readonly DispatcherTimer _timer = new DispatcherTimer();

        private void LoadResource()
        {
            
        }

        public MainWindow()
        {
            InitializeComponent();
            GC.Collect();

            _instance = this;

            LoadResource();
            
            //打开数据库连接
            XMLHelper xmlOper = new XMLHelper();
            String dataAccess = null;
            
            //ConnectDatabase.getInstance().setConnetion(ConfigurationManager.AppSettings["DataAddress"]);  
            String dataProvider = xmlOper.GetXmlNodeAttribute("SmartMD.Manager.vshost.exe.config", "configuration/appSettings/add[@key='dataProvider']", "value");
            if (dataProvider == "Oracle")
            {
                dataAccess = xmlOper.GetXmlNodeAttribute("SmartMD.Manager.vshost.exe.config", "configuration/appSettings/add[@key='DataAddress']", "value");
                ConnectDatabase.getInstance().setConnetion(dataAccess);
            }
            else
            {
                dataAccess = xmlOper.GetXmlNodeAttribute("SmartMD.Manager.vshost.exe.config", "configuration/appSettings/add[@key='PostgresqlAddress']", "value");
                DbConnection.getInstance().setConnetion(dataAccess);
            }
            //加载缓存
            CacheUtil.GetInstance().Init();
            //设置连接状态
            SingletonManager.Online = true; 
        }

        public void Init()
        {

            Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在连接后台服务......";
            string errMessage;
            TestServiceConnect(out errMessage);

            Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在显示主窗口......";

            //Toolbox.Instance.ToolTip = "工具箱";

            Techstar.Windows.SplashScreen.CurrentSplash.Message = "正在注册控件...";

           // Toolbox.Instance.PopulateToolbox();

            RegisgerForm();
            _timer.Interval = TimeSpan.FromMilliseconds(100);
            _timer.Tick += TimerTick;
            _timer.Start();

        }

        private static void ProcessPad(Stema.Controls.NavigationPane panel)
        {
            foreach (BasePad item in panel.Items)
            {
                item.Visibility = item.CanShow ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }

            var items = (from item in panel.Items.OfType<BasePad>() where item.CanShow select item).ToList();
            panel.Visibility = items.Count() > 0 ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;

            if (items.Count() > 0 && (panel.SelectedItem == null || ((BasePad)panel.SelectedItem).Visibility == System.Windows.Visibility.Collapsed))
            {
                panel.SelectedItem = items[0];
            }
        }

        private void TimerTick(object sender, EventArgs e)
        {
            ProcessPad(panelLeft);
            ProcessPad(panelRight);

            foreach (var form in BaseWindow.Instances)
            {
                form.RefreshRibbonPageState();
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            
            Show(StartPageWindow.ModuleName);
        }

        protected override void OnClosed(EventArgs e)
        {
            try
            {
                RecentPanel.Save();
                //用户退出
                DataServiceManager.UserService.SetUserLogoutFlag(MainWindow.CurrentUser.Name);

                _timer.Stop();
                base.OnClosed(e);
                Process.GetCurrentProcess().Kill();
            }
            catch { }
        }
        //注册窗口
        private static void RegisgerForm()
        {
            DocumentManager.Register(ReportAnalysisWindow.ModuleName, typeof(ReportAnalysisWindow));
            DocumentManager.Register(StartPageWindow.ModuleName, typeof(StartPageWindow));
            DocumentManager.Register(SpecManagerWindow.ModuleName, typeof(SpecManagerWindow));
            DocumentManager.Register(PatientManagerWindow.ModuleName, typeof(PatientManagerWindow));
     
            DocumentManager.Register(ExamItemMaintain.ModuleName, typeof(ExamItemMaintain));
            DocumentManager.Register(SystemWindow.ModuleName, typeof(SystemWindow));
            DocumentManager.Register(DataDictWindow.ModuleName, typeof(DataDictWindow));
            DocumentManager.Register(ContainerModelPanel.ModuleName, typeof(ContainerModelPanel));
            DocumentManager.Register(UserManagerWindow.ModuleName, typeof(UserManagerWindow));
            DocumentManager.Register(FollowupInfoStatisticWnd.ModuleName, typeof(FollowupInfoStatisticWnd));
            DocumentManager.Register(ContainerModelMaintain.ModuleName, typeof(ContainerModelMaintain));             
            
        }

        public static MainWindow Instance
        {
            get
            {
                return _instance;
            }
        }

        public static bool OnLine
        {
            get { return _onLine; }
        }

        public static UserInfo CurrentUser { get; set; }

        public static void AddLeftPad(BasePad pad)
        {
            RemovePad(pad);
            pad.FlowDirection = FlowDirection.LeftToRight;
            MainWindow.Instance.panelLeft.Items.Add(pad);

        }

        public static void AddRightPad(BasePad pad)
        {
            RemovePad(pad);
            pad.FlowDirection = FlowDirection.LeftToRight;
            MainWindow.Instance.panelRight.Items.Add(pad);
        }

        public static void RemovePad(BasePad pad)
        {
            if (MainWindow.Instance.panelLeft.Items.IndexOf(pad) >= 0)
                MainWindow.Instance.panelLeft.Items.Remove(pad);
            else if (MainWindow.Instance.panelRight.Items.IndexOf(pad) >= 0)
                MainWindow.Instance.panelRight.Items.Remove(pad);
        }

        public bool TestServiceConnect(out string errMessage)
        {
            errMessage = "";
            return false;
        }

        public void SetState(bool online)
        {
            _onLine = online;
            if (online)
            {
                this.btnServer.Icon = GetImageResource("/Images/server_ok.png");
                this.btnServer.Header = "连接成功";
            }
            else
            {
                this.btnServer.Icon = GetImageResource("/Images/server_error.png");
                this.btnServer.Header = "连接失败";
            }
            SingletonManager.Online = online;
        }
        
        private void btnSpecManagerClick(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(SpecManagerWindow.ModuleName);
        }

        private void btnPatientManagerClick(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(PatientManagerWindow.ModuleName);
        }
    
        private void BtnReportAnalysisClick(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(ReportAnalysisWindow.ModuleName);
        }
        
        private void btnConnectClick(object sender, RoutedEventArgs e)
        {
            ProgressThread thread = new ProgressThread(220);

            thread.Start("连接测试", "正在连接后台服务......");
            string errMessage;
            if (!TestServiceConnect(out errMessage))
            {
                thread.End();
                TaskDialogEx.Error("后台服务", errMessage);
            }
            else
            {
                thread.End();
                TaskDialogEx.Information("后台服务", "连接成功");
            }
        }

        private void BtnExitClick(object sender, RoutedEventArgs e)
        {
            //用户退出
            DataServiceManager.UserService.SetUserLogoutFlag(MainWindow.CurrentUser.Name);
            //关闭数据库连接
            ConnectDatabase.getInstance().closeConnetion();
            this.Close();
        }

        #region DocumentManager.Show
        public static DocumentContent Show(string name)
        {
            return Show(name, name);
        }

        public static DocumentContent Show(string name, string label)
        {
            return Show<DocumentContent>(name, label);
        }

        public static T Show<T>(string name) where T : DocumentContent
        {
            return Show<T>(name, name);
        }

        public static T Show<T>(string name, string label) where T : DocumentContent
        {
            return DocumentManager.Show<T>(Instance.DocumentHost, name, label);
        }
        #endregion

        
        public static Stream GetResourceStream(string path)
        {
            var result = Application.GetResourceStream(new Uri(path, UriKind.Relative));
            if (result == null)
                return null;
            return result.Stream;
        }

        public static BitmapImage GetImageResource(string path)
        {
            var stream = GetResourceStream(path);
            if (stream == null) return null;
            var result = new BitmapImage();
            result.BeginInit();
            result.StreamSource = stream;
            result.EndInit();
            return result;
        }   

        private void BtnSysvariableClick(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(NewContainerPanel.ModuleName);
        }

        /**
         * 功能：数据字典
         * 
         * */
        private void btnDataDict_Click(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(SmartMD.Manager.SysInfo.DataDictWindow.ModuleName);
        }
        /**
         * 功能：用户管理
         * 
         * */
        private void BtnUserManager_Click(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(SmartMD.Manager.SysInfo.User.UserManagerWindow.ModuleName);
        }

        private void btnReportStatistic_Click(object sender, RoutedEventArgs e)
        {
            MainWindow.Show(SmartMD.Manager.Patient.FollowupInfoStatisticWnd.ModuleName);           
        }
        
    }
}